<template>
	<view>
		<custom title="快捷记分" borderBottom="1px solid #f7f7f7"></custom>
		<!-- 用户 -->
		<view style="padding: 40rpx 20rpx;margin-top: -20rpx;" v-if="tool_1_game.status === 0">
			<text style="font-size: 28rpx;color:#999;">添加玩家姓名，点击完成开始记分</text>
			<!-- 列表 -->
			<view class="user-list">
				<view v-for="(item,index) in tool_1_game.users" :key="item.id" class="user-item">
					<image src="/static/user.png" class="t-image"></image>
					<input placeholder="请输入玩家姓名" class="t-input" v-model="item.name" />
					<view @tap.stop="delete_user(index)" class="t-delete hover-o">
						<text class="t-delete-text">删除</text>
					</view>
				</view>
			</view>

			<view @tap.stop="add_user" class="add-user-btn hover-o" style="background-color: #ccc;">
				<text class="a-text">添加玩家</text>
			</view>
			<view @tap.stop="start_game" class="add-user-btn hover-o">
				<text class="a-text">完成</text>
			</view>
		</view>



		<!-- 列表 -->
		<view v-if="tool_1_game.status !== 0">
			<view class="users-header" :style="{top:customBar}" style="z-index: 44;">
				<text class="step-item" style="background-color: rgba(0,0,0,0);color:#FFF;opacity: 0.5;">姓名</text>
				<text @tap.stop="editPlayerName(index)" class="users-item" style="font-size:30rpx;"
					v-for="(item,index) in tool_1_game.users" :key="item.id">{{item.name}}</text>
			</view>
			<view class="users-line"
				:style=" active_line === index?'background-color:#ff8686': index%2===0?'background-color:#f7f7f7':'background-color:#FFF'"
				v-for="(item,index) in tool_1_game.history" @longpress="deleteHistoryList(index)">
				<text class="step-item number-font">{{index+1}}</text>
				<text class="users-line-num number-font" v-for="(item1,index1) in tool_1_game.users.length" :key="index"
					:style="item[index1]>0?'color:#4073ff;':'color:#666;'">{{item[index1]}}</text>
			</view>
			<view class="users-header" style="position: relative;" v-if="tool_1_game.history.length>0">
				<text class="step-item" tyle="background-color: rgba(255,255,255,1);color:#333;">总计</text>
				<text class="users-item number-font" v-for="(item,index) in get_total()" :key="item.id">{{item}}</text>
			</view>
			<view style="height: 880rpx;"></view>
		</view>



		<!-- 记分 -->
		<view class="tool-box" v-if="tool_1_game.status === 1">
			<view @tap.stop="other_tool" class="tool-one hover-o" style="background-color: #ccc;">
				<text class="tool-one-text">完成</text>
			</view>
			<view class="tool-one hover-o" @tap.stop="Add">
				<text class="tool-one-text">记分</text>
			</view>
		</view>
		<password @clearAll="clearAll" @delete="s_delete" @add="s_add" @sure="s_sure" :showSure="true" ref="password">

			<view class="user-list">
				<view @tap.stop="choose_index(index)" v-for="(item,index) in tool_1_game.users" :key="item.id"
					:style="index==source_index?'background-color:rgba(110,62,204,0.1);':'background-color:#f7f7f7;'"
					class="user-item"
					style="background-color: #f7f7f7;border-radius: 0;margin: 0;border-bottom: 0.5px solid rgba(0,0,0,0.06);">
					<image src="/static/user.png" class="t-image"></image>
					<text style="padding-left: 40rpx;flex:1;font-size: 30rpx;font-weight: bold;">{{item.name}}</text>
					<view @tap.stop="choose_index(index)" class="t-input number-font flex flex-x-y"
						:style="source_arr[index] !== ''?'':'font-size:30rpx;'"
						style="font-size: 36rpx;align-items: center;align-items: center;flex:none;width:250rpx;background-color: #FFF;text-align: center;">
						{{source_arr[index] !== ''?source_arr[index]:'请输入分数'}}
					</view>
				</view>
			</view>

		</password>
	</view>
</template>

<script>
	import {
		showToast,
		dateFormat
	} from '@/utils';
	export default {
		data() {
			return {
				customBar: getApp().globalData.customBar + 'px',
				tool_1_game: {
					status: 0, //0未开始   1已开始   2已结束
					users: [
						//
						{
							name: '',
							id: 1,
						},
						{
							name: '',
							id: 2,
						},
						{
							name: '',
							id: 3,
						},
						{
							name: '',
							id: 4,
						}
					],
					history: [


					],
					startTime: null,
					endTime: null,
				},
				source_index: 0, //输入光标
				source_arr: ['', '', '', ''],
				active_line: -1,
			}
		},
		onLoad(e) {
			let tool_1_game = uni.getStorageSync('tool_1_game') || null;
			if (e.id) {
				uni.setNavigationBarTitle({
					title: '记分详情'
				});
				tool_1_game = uni.getStorageSync(e.id) || tool_1_game;
			}
			if (!tool_1_game) {
				//开始
				return;
			} else {
				this.tool_1_game = tool_1_game;
			}
		},
		methods: {
			openPassword() {
				this.$refs.password.open();
			},
			add_user() {
				this.tool_1_game.users.push({
					name: '',
					id: new Date().getTime(),
				});
			},
			delete_user(index) {
				uni.hideKeyboard();
				this.tool_1_game.users.splice(index, 1);
			},
			start_game() {
				uni.hideKeyboard();
				if (this.tool_1_game.users.filter(v => String(v.name).trim()).length == 0) {
					showToast('请输入玩家姓名', 2500);
					return;
				}
				uni.showModal({
					title: '提示',
					content: "确定开始记分?",
					success: res => {
						if (res.confirm) {
							this.tool_1_game.users = this.tool_1_game.users.map(v => {
								v.name = String(v.name).trim();
								return v;
							}).filter(v => v.name);
							this.tool_1_game.status = 1;
							this.tool_1_game.startTime = new Date().getTime();
							this.save_catch();
						}
					}
				})

			},
			get_total() {
				let arr = new Array(this.tool_1_game.users.length).fill(0);
				this.tool_1_game.history.forEach((item, value) => {
					item.forEach((v, i) => {
						arr[i] += Number(v);
					});
				});
				return arr;

			},
			Add() {
				this.source_index = 0;
				this.source_arr = new Array(this.tool_1_game.users.length).fill('');
				this.$refs.password.open();
			},
			choose_index(i) {
				this.source_index = i;
				uni.vibrateShort();
			},
			isNumeric(value) {
				return /^-?\d+$/.test(value);
			},
			//修改玩家姓名
			editPlayerName(index) {
				if (this.tool_1_game.status !== 1) return;
				uni.showModal({
					title: '提示',
					content: `是否修改 ${this.tool_1_game.users[index].name} 的玩家姓名?`,
					success: res => {
						if (res.confirm) {
							getApp().globalData.EDIT_BACK = (name) => {
								this.tool_1_game.users[index].name = name;
								this.save_catch();
							}
							uni.navigateTo({
								url: `/pages/edit-name/edit-name?name=${this.tool_1_game.users[index].name}`
							});
						}
					}
				})

			},
			s_sure() {
				//差一个值 自动计算
				if (this.source_arr.filter(v => v !== '').length === this.source_arr.length - 1) {
					let a = this.source_arr.reduce((a, b) => Number(a) + Number(b), 0);

					this.source_arr.some((v, i) => {
						if (v === '') {
							this.$set(this.source_arr, i, (0 - a).toString());
							this.source_index = i;
						}
					});


					return;
				}

				if (this.source_arr.filter(v => v !== '').length != this.source_arr.length) {
					//未输入完整
					this.source_arr.some((v, index) => {
						if (v === '' && index > this.source_index) {
							this.source_index = index;

							return true;
						} else if (index == this.source_arr.length - 1) {
							//到底最后一个了
							this.source_index = -1;
							this.s_sure();
						}
					});

					return;
				}


				let a = 0;
				let b = 0;
				let s = true;
				this.source_arr.forEach(v => {
					if (this.isNumeric(v)) {
						let value = Number(v);
						if (value < 0) {
							b += value;
						} else {
							a += value;
						}
					} else {
						s = false;
					}

				})
				if (!s) {
					showToast('请输入数字');
					return;
				}
				if (a + b !== 0) {
					showToast('输入有误');
					return;
				}

				this.$refs.password.close();
				this.tool_1_game.history.push(JSON.parse(JSON.stringify(this.source_arr)));
				this.save_catch();

			},

			s_add(i) {
				this.source_arr[this.source_index] += i;

				this.$set(this.source_arr, this.source_index, this.source_arr[this.source_index]);
			},
			s_delete() {
				let str = this.source_arr[this.source_index];
				if (str.length === 0) return;
				this.source_arr[this.source_index] = str.slice(0, -1)
				this.$set(this.source_arr, this.source_index, this.source_arr[this.source_index]);
			},
			clearAll() {
				this.$set(this.source_arr, this.source_index, '');
			},
			other_tool() {
				let handel = [
					//
					{
						name: '清除数据，重新开始',
						key: 'clear',
					},
					{
						name: '删除对局，返回到首页',
						key: 'exit',
					},
					{
						name: '已经打完了，去结算',
						key: 'success',
					},
				];

				// this.requestLoading = false;
				// this.tool_1_game.status = 3;
				//保持
				uni.showActionSheet({
					itemList: handel.map(v => v.name),
					success: res => {
						let index = res.tapIndex;
						uni.showModal({
							title: '提示',
							content: `是否${handel[index].name}?`,
							success: r => {
								if (r.confirm) {

									////////////////////
									if (handel[index].key === 'clear') {
										this.tool_1_game.history = [];
										return;
									}
									if (handel[index].key === 'exit') {
										uni.setStorageSync('tool_1_game', '');
										uni.navigateBack({
											fail: () => {
												uni.reLaunch({
													url: '/pages/index/index'
												})
											}
										});
										return;
									}
									if (handel[index].key === 'success') {
										if (this.tool_1_game.history.length == 0) {
											showToast('至少需要一条记分数据，才能完成结算');
											return;
										}
										this.tool_1_game.status = 2;
										this.tool_1_game.endTime = new Date().getTime();
										this.endGame();
										return;
									}
									////////////////////


								}
							}
						})
					}
				})
			},
			save_catch() {
				uni.setStorage({
					key: 'tool_1_game',
					data: this.tool_1_game,
				});
			},
			deleteHistoryList(index) {
				if (this.tool_1_game.status !== 1) return;
				this.active_line = index;
				uni.showModal({
					title: '提示',
					content: `是否删除第${index+1}条数据?`,
					success: res => {
						if (res.confirm) {
							this.tool_1_game.history.splice(index, 1);
							this.save_catch();
						}
					},
					complete: () => {
						this.active_line = -1;
					}
				})
			},
			endGame() {
				let tool_1_game_history = uni.getStorageSync('tool_1_game_history') || [];
				let get_total = this.get_total();

				let id = this.tool_1_game.endTime;
				tool_1_game_history.unshift({
					id,
					name: `${this.tool_1_game.users.map(v=>v.name).join('、')}在${dateFormat('YYYY年mm月dd日HH时MM分',new Date(id))}的对局`,
					ranking: this.tool_1_game.users.map((v, i) => {
						return {
							name: v.name,
							num: get_total[i],
						}
					}).sort((a, b) => a.num - b.num >= 0 ? -1 : 1),
					type: 1,
					time: dateFormat('YYYY-mm-dd HH:MM', new Date(id))
				});
				uni.setStorageSync(id.toString(), JSON.parse(JSON.stringify(this.tool_1_game)));
				uni.setStorageSync('tool_1_game_history', tool_1_game_history);
				uni.setStorageSync('tool_1_game', '');
				console.log(tool_1_game_history);
				uni.redirectTo({
					url: `/pages/ranking/ranking?id=${id}`
				});
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: $theme-background-color;
	}

	.user-item {
		padding: 40rpx;
		background-color: #FFF;
		border-radius: 20rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-top: 20rpx;
	}

	.t-image {
		width: 60rpx;
		height: 60rpx;
	}

	.t-input {
		background-color: #f7f7f7;
		height: 70rpx;
		border-radius: 4rpx;
		flex: 1;
		margin-left: 20rpx;
		color: #333;
		font-size: 28rpx;
		padding: 0 20rpx;
	}

	.t-delete-text {
		color: #F00;
		font-size: 28rpx;
		padding-left: 40rpx;
	}

	.add-user-btn {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 20rpx;
		height: 100rpx;
		background-color: #fd7f00;
		border-radius: 50rpx;
	}

	.a-text {
		color: #Fff;
		font-size: 36rpx;
	}

	.tool-box {
		position: fixed;
		right: 40rpx;
		bottom: 600rpx;
	}

	.tool-one {
		width: 100rpx;
		height: 100rpx;
		background-color: #fd7f00;
		border-radius: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 40rpx;
		box-shadow: 0px 0 6rpx rgba(0, 0, 0, 0.08);
	}

	.tool-one-text {
		font-size: 28rpx;
		font-weight: bold;
		color: #fff;
	}

	.users-header {
		padding: 20rpx;
		display: flex;
		flex-direction: row;
		position: sticky;
		top: 0;
		align-items: center;
		background-color: $theme-color;
	}

	.users-item {
		color: #fff;
		font-size: 36rpx;
		flex: 1;
		justify-content: center;
		align-items: center;
		font-weight: bold;
		text-align: center;
	}

	.users-line {
		padding: 20rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		transition: all 0.25s;
	}

	.users-line-num {
		color: #333;
		font-size: 36rpx;
		flex: 1;
		justify-content: center;
		align-items: center;
		font-weight: bold;
		text-align: center;

	}

	.step-item {
		color: #666;
		font-size: 24rpx;
		text-align: center;
		width: 60rpx;
		height: 60rpx;
		background-color: #efefef;
		display: flex;
		justify-content: center;
		align-items: center;
		line-height: 60rpx;
		border-radius: 50%;
		font-weight: bold;
	}
</style>